/***************************************************************************
 *   Copyright (C) 2006 by Sergey Melderis   *
 *   sergey.melderis@gmail.com   *
 *                                                                         *
 *   This program is free software; you can redistribute it and/or modify  *
 *   it under the terms of the GNU General Public License as published by  *
 *   the Free Software Foundation; either version 2 of the License, or     *
 *   (at your option) any later version.                                   *
 *                                                                         *
 *   This program is distributed in the hope that it will be useful,       *
 *   but WITHOUT ANY WARRANTY; without even the implied warranty of        *
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *
 *   GNU General Public License for more details.                          *
 *                                                                         *
 *   You should have received a copy of the GNU General Public License     *
 *   along with this program; if not, write to the                         *
 *   Free Software Foundation, Inc.,                                       *
 *   59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.             *
 ***************************************************************************/
#include "wordquizfilechooser.h"
#include <kurlrequesterdlg.h>
#include <qdeepcopy.h>        
#include <qlistbox.h>
#include <qstringlist.h>
#include <qlabel.h>
#include <qlayout.h>
#include <kurlrequester.h>
#include <qstring.h>
#include <qlineedit.h>
#include <kaccelmanager.h>
#include <klocale.h>
#include <klineedit.h>
#include <qwhatsthis.h>        
#include "filesprefs.h"
WordQuizFileChooser::WordQuizFileChooser(QWidget *parent, const char *name)
    : KDialogBase(KDialogBase::Plain, "Edit WordQuiz Files", 0,
                  KDialogBase::NoDefault,
                  parent, name, true)
{
    // The following code is addapted from KAddressBook EmailEditDialog
    QWidget *page = plainPage();

    QGridLayout *topLayout = new QGridLayout( page, 4, 3, 0, spacingHint() );

    m_filesListBox = new QListBox( page );

    // Make sure there is room for the scrollbar
    m_filesListBox->setMinimumHeight(m_filesListBox->sizeHint().height() + 30);
    connect(m_filesListBox, SIGNAL( highlighted(int)),
               SLOT(selectionChanged(int)));
    connect( m_filesListBox, SIGNAL(selected(int)),
                SLOT( edit() ) );
    topLayout->addMultiCellWidget(m_filesListBox, 0, 3, 0, 1);

    m_addButton = new QPushButton( i18n( "Add..." ), page );
    connect( m_addButton, SIGNAL( clicked() ), SLOT( add() ) );
    topLayout->addWidget( m_addButton, 0, 2 );

    m_editButton = new QPushButton( i18n( "Edit..." ), page );
    connect( m_editButton, SIGNAL( clicked() ), SLOT( edit() ) );
    topLayout->addWidget( m_editButton, 1, 2 );

    m_removeButton = new QPushButton( i18n( "Remove" ), page );
    connect( m_removeButton, SIGNAL( clicked() ), SLOT( remove() ) );
    topLayout->addWidget( m_removeButton, 2, 2 );

    topLayout->activate();

    QMap<QString, QString> files = FilesPrefs::self().keyUrlItems();
    QMap<QString, QString>::const_iterator iter;
    for (iter = files.begin(); iter != files.end(); ++iter) {
        m_filesListBox->insertItem(iter.key());
    }

    // set default state
    selectionChanged( -1 );
    KAcceleratorManager::manage( this );

    m_changed = false;
    setInitialSize( QSize( 400, 200 ) );
}


WordQuizFileChooser::~WordQuizFileChooser()
{
}

void WordQuizFileChooser::add()
{
    KeyFileName pair = KeyUrlDialog::getKeyUrlPair(QString::null, QString::null, this);

    QString key = pair.first;
    QString url = pair.second;
    if (key == QString::null && url == QString::null)
        return;
    if (FilesPrefs::self().hasKey(key)) {
        if (FilesPrefs::self().hasKeyAndUrl(key, url))
            return;
            key = key + "(1)";
        }
        
    m_filesListBox->insertItem(key);
    FilesPrefs::self().setKeyUrlItem(key, url);
    emit selectionChanged(true);
    
}

void WordQuizFileChooser::edit()
{
    int current = m_filesListBox->currentItem();
    QString text = m_filesListBox->currentText();
    KeyFileName pair =
            KeyUrlDialog::getKeyUrlPair(text, FilesPrefs::self().keyUrlItems()[text], this);
    if (pair.first == text && FilesPrefs::self().keyUrlItems()[text] == pair.second)
        m_changed = false;
    else {
        m_filesListBox->changeItem(pair.first, current);
        m_filesListBox->triggerUpdate(true);
        FilesPrefs::self().removeKey(text); 
        FilesPrefs::self().setKeyUrlItem(pair.first, pair.second);
        m_changed = true;
    }
    if (m_changed)
        emit selectionChanged(true);
}

void WordQuizFileChooser::remove()
{
    FilesPrefs::self().removeKey(m_filesListBox->currentText());
    m_filesListBox->removeItem(m_filesListBox->currentItem());
    emit selectionChanged(true);    
}

void WordQuizFileChooser::selectionChanged(int index)
{
  bool value = ( index >= 0 ); // An item is selected

  m_removeButton->setEnabled(value);
  m_editButton->setEnabled(value);
}



KeyUrlDialog::KeyUrlDialog(const QString &url, const QString &urlName,
                             QWidget *parent, const char *name)
    :KDialogBase( Plain, QString::null, Ok|Cancel|User1, Ok, parent, name,
                  true, true, KStdGuiItem::clear() )
    
{
    initDialog(url, urlName);
}

KeyUrlDialog::~KeyUrlDialog()
{
}

void KeyUrlDialog::initDialog(const QString &key, const QString &url)
{
    QWidget *page = plainPage();
    QVBoxLayout * topLayout = new QVBoxLayout( page, 0);
    QLabel *titleLabel = new QLabel("Title:" , page);
    QWhatsThis::add(titleLabel, "Give a title for Your KWordQuiz file that will be shown in the menu.");
    topLayout->addWidget(titleLabel);
    m_keyLineEdit = new QLineEdit(key, page);
    topLayout->addWidget(m_keyLineEdit);

    // Add some spacing
    topLayout->addSpacing(15);

    QLabel *urlLabel = new QLabel("Location:", page);
    QWhatsThis::add(urlLabel, "Select Your KWordQuiz file.");
    topLayout->addWidget(urlLabel);
    m_urlRequester = new KURLRequester( url, page, "urlRequester" );
    m_urlRequester->setMinimumWidth(m_urlRequester->sizeHint().width() * 2);
    m_keyLineEdit->setMinimumWidth(m_urlRequester->width());
    topLayout->addWidget( m_urlRequester );
    m_urlRequester->setFocus();
    connect(m_urlRequester->lineEdit(), SIGNAL(textChanged(const QString&)),
            SLOT(slotTextChanged(const QString&)) );
    bool state = !key.isEmpty() && !url.isEmpty() ;

    enableButtonOK( state );
    enableButton( KDialogBase::User1, state );
    connect(this, SIGNAL(user1Clicked()), SLOT(clear()) );
}

void KeyUrlDialog::clear()
{
    m_keyLineEdit->clear();
    m_urlRequester->clear();
}

void KeyUrlDialog::slotTextChanged(const QString &text)
{
    QString _text = text.stripWhiteSpace();
    bool state = !_text.isEmpty() && _text.endsWith(".kvtml", TRUE) && QFile::exists(_text);
    // If there is url selection, but no name for url, let's suggest one.
    if (state && m_keyLineEdit->text().stripWhiteSpace().isEmpty()) {
        int lastSlashIndex = _text.findRev("/");
        if (lastSlashIndex != -1) {
            QString suggestName = _text.replace(0, lastSlashIndex + 1, "");
            int indexOfDot = _text.findRev(".");
            if (indexOfDot != -1) {
                suggestName = suggestName.remove(indexOfDot, suggestName.length());
            }
            m_keyLineEdit->setText(suggestName);
        }
    }
    enableButtonOK( state );
    enableButton( KDialogBase::User1, state );
}

QString KeyUrlDialog::selectedUrl() const
{
     if (result() == QDialog::Accepted)
         return m_urlRequester->url();
     else
         return QString();
}

QString KeyUrlDialog::key() const
{
    if (result() == QDialog::Accepted)
        return m_keyLineEdit->text();
    else
        return QString();
}

KeyFileName KeyUrlDialog::getKeyUrlPair(const QString &key, const QString &url,
                QWidget *parent)
{
    KeyUrlDialog dlg(key, url, parent);
    dlg.setCaption("Open");
    KeyFileName pair = qMakePair(key, url);
    bool ok = (dlg.exec() == QDialog::Accepted);
    if (ok) {
        pair.second = dlg.selectedUrl();
        pair.first = dlg.key();
    }
    return pair;
}

#include "wordquizfilechooser.moc"
